Golang Web request Parameter Validation

Source: Internet
Author: User

based on the actual development of the Golang Web project, the client request parameters are validated in the controller layer, which leads to the high redundancy of controller layer code and affects the development efficiency. code example:

    feedback := &mysql_model.OfbankFeedback{}    err := json.Unmarshal(body, feedback)    feedback.FStatus=1    feedback.CreateTime=time.Now()    if err != nil {        resp := apiservice.GenerateResponse(0, "请求参数有误", "")        rw.Write([]byte(resp))        return    }    if feedback.Phone=="" {        resp := apiservice.GenerateResponse(0, "参数phone不能为空", "")        rw.Write([]byte(resp))        return    }    if feedback.Contacts=="" {        resp := apiservice.GenerateResponse(0, "参数contacts不能为空", "")        rw.Write([]byte(resp))        return    }    if feedback.FType==0 {        resp := apiservice.GenerateResponse(0, "参数fType不能为空", "")        rw.Write([]byte(resp))        return    }    if feedback.Img==""&&feedback.Content=="" {        resp := apiservice.GenerateResponse(0, "参数img或content不能同时为空", "")        rw.Write([]byte(resp))        return    }

High code redundancy? Impact on development efficiency? How to solve?

There are many web frameworks (Beego, Faygo, etc.) that support structural parameter validation, a framework for solving project management problems, and the extensibility of parameter validation rules in the framework is not very good, the personal feeling is not very elegant, so I wrote a structure parameter verification tool (struct_ UTIL.GO)

code example:

/** * Created with IntelliJ idea. * Description: * User:yangzhao * DATE:2018-07-17 * time:11:08 */package utilsimport ("Reflect" "errors" "Stri NGS "" StrConv ")//custom validation Rule const (Not_empty =" Notempty "//string cannot be empty Int_max =" Int-max "//int max int_min =" Int-m     In "//int minimum value type =" type "//Type Str_max_length =" Str-max-len "//string Maximum length Str_min_length =" Str-min-len "//String Minimum length Str_length = "Str-len"//String length range = "range"//element must be within the appropriate range example: 1-100)//External exposure structure experience function Func structvalidate (Bean INTERFAC e{}) Error {fields: = reflect. ValueOf (Bean). Elem () for I: = 0; I < fields. Numfield (); i++ {field: = fields. Type (). field (i) Valid: = field. Tag.get ("valid") if valid = = "" {continue} Value: = Fields. Fieldbyname (field. Name) Err: = Fieldvalidate (field. Name, valid, value) if err! = Nil {return err}} return nil}//property validates func fieldvalidate (fiel Dname, valid string, value reflect. Value)Error {valids: = strings. Split (valid, "") for _, Valid: = Range Valids {if strings. Index (valid, TYPE)! =-1 {V: = value. Type (). Name () Split: = Strings. Split (valid, "=") T: = split[1] If v! = t {return errors. New (fieldName + "type must is" + t)}} if strings. Index (valid, not_empty)! =-1 {str: = value. String () if str = = "" {return errors. New (FieldName + "value not Empty")}} if strings. Index (valid, int_min)! =-1 {V: = value. Int () Split: = Strings. Split (valid, "=") rule, err: = StrConv. Atoi (split[1]) if err! = Nil {return errors. New (FieldName + ": Validation rule Error")} if int (v) < rule {return errors. New (FieldName + "value must >=" + StrConv. Itoa (rule)}} if strings.    Index (valid, int_max)! =-1 {        V: = value. Int () Split: = Strings. Split (valid, "=") rule, err: = StrConv. Atoi (split[1]) if err! = Nil {return errors. New (FieldName + ": Validation rule Error")} if int (v) > rule {return errors. New (FieldName + "value must <=" + StrConv. Itoa (Rule)}}}//String special handling if value. Type (). Name () = = "string" {if strings. Index (valid, str_length)! =-1 {V: = value. String () Split: = Strings. Split (valid, "=") Lenstr: = split[1] length, err: = StrConv. Atoi (LENSTR) if err! = Nil {return errors.                    New (FieldName + "" + str_length + "rule is Error")} If Len (v)! = LENGTH { return errors. New (fieldName + "str length must be" + Lenstr)}} if strings.               Index (valid, str_max_length)! =-1 { V: = value. String () Split: = Strings. Split (valid, "=") Lenstr: = split[1] length, err: = StrConv. Atoi (LENSTR) if err! = Nil {return errors.                    New (fieldName + "+ str_length +" rule is Error ")} If Len (v) > LENGTH { return errors. New (fieldName + "str length <=" + Lenstr)}} if strings. Index (valid, str_min_length)! =-1 {V: = value. String () Split: = Strings. Split (valid, "=") Lenstr: = split[1] length, err: = StrConv. Atoi (LENSTR) if err! = Nil {return errors.                    New (fieldName + "+ str_length +" rule is Error ")} If Len (v) < LENGTH { return errors. New (fieldName + "str length >=" + Lenstr)}}} return nil}

Above belongs to original article, reprint please specify author @ strange coffee
qq:208275451

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.