Summary of common code snippets in development of golang

Time:2020-3-10

This article mainly summarizes the code snippets I used when I wrote the golang application, which are provided for future use, and also for reference and learning to the friends who need it. Let’s have a look at the details:

1、 Send user: passwd information through HTTP package

Send a request similar to curl-u
 client := &http.Client{}
 req, err := http.NewRequest("GET", <url>, nil)
 req.SetBasicAuth(<username>, <userpasswd>)
 if err != nil {
  log.Fatal(err)
 }

 resp, err := client.Do(req)
 if err != nil {
  log.Fatal(err)
 }
 content, err := ioutil.ReadAll(resp.Body)
 if err != nil {
  log.Fatal(err)
 }

2、 Golang converts unknown objects to array by reflection


func interfaceSlice(slice interface{}) []interface{} { 
 s := reflect.ValueOf(slice)
 if s.Kind() != reflect.Slice {
  panic("InterfaceSlice() given a non-slice type")
 }

 ret := make([]interface{}, s.Len())

 for i := 0; i < s.Len(); i++ {
  ret[i] = s.Index(i).Interface()
 }

 return ret
}

3、 MUX get get query parameter


 vals := r.URL.Query()
 oriDriver, ok := vals["driver"]

4、 MUX cross domain access code


  methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
 headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
 originsOk := handlers.AllowedOrigins([]string{"*"})
 log.Println(http.ListenAndServe(":8000", handlers.CORS(headersOk, originsOk, methodsOk)(r)))

5、 Recursively find files

func readAPK(path string, apk map[string]int) {
 //FMT. Println ("processing", path)
 files, _ := ioutil.ReadDir(path)
 for _, file := range files {
  // fmt.Println(file.Name(), file.IsDir())
  if file.IsDir() {
   readAPK(path+"/"+file.Name(), apk)
  } else {
   if strings.Compare(file.Name(), "APK.log") == 0 {
    ap := make(map[string]string)
    body, err := ioutil.ReadFile(path + "/" + file.Name())
    if err != nil {
     FMT. Printf ("[% s] failed to read [% s] \ n", file. Name(), err. Error())
     return
    }

    err = json.Unmarshal(body, &ap)
    if err != nil {
     FMT. Printf ("[% s] failed to parse [% s] \ n", file. Name(), err. Error())
     return
    }

    for a := range ap {
     at := strings.Split(ap[a], "|+|")
     for _, atemp := range at {
      info := strings.Split(atemp, "|-|")
      if len(info) > 1 {
       header := strings.Split(info[1], " ")
       for _, h := range header {
        if strings.Contains(h, "Referer:") {
         u, err := url.ParseRequestURI(h[8:])
         if err != nil {
          fmt.Println(err.Error())
         } else {
          apk[u.Host]++
         }
        }
       }
      }

     }
    }
   }
  }
 }
}

6、 Analyze the existing data of Mongo


type App struct { 
 Id string `json:"id" bson:"_id,omitempty"`
 User_id string `bson:"user_id"`
 Name string `bson:"name"`
 Domain string `bson:"domain"`
 Business_line string `bson:"business_line"`
}

A key:

1. Use the bson modifier

2. Each flag is directly separated by a space

3. Use “Id” and “omitempty”, split. No spaces at the same time

7、 Timer

for {
  now := time.Now()
  next := now.Add(time.Minute * 10)
  next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), next.Minute(), 0, 0, next.Location())
  t := time.NewTimer(next.Sub(now))
  Log.printf ("next collection time is [% s] \ n", next. Format ("200601021504"))

  select {
  case <-t.C:
   err := sync.Gather()
   if err != nil {
    log.Println(err)
   }
  }
 }

summary

The above is the whole content of this article. I hope that the content of this article can bring some help to your study or work. If you have any questions, you can leave a message and communicate with us. Thank you for your support for developpaer.

Recommended Today

asp.net Application of regular expression

1. Balanced group / recursive matching (?’ Group ‘), which is called the corresponding content of group, and counts it on the stack;(?’- Group ‘), and count the corresponding content named group out of the stack(?!) Zero width negative look ahead assertion. Since there is no suffix expression, attempts to match always failRegular example:,{0,1}”5″:\[[^\[\]]*(((?’Open’\[)[^\[\]]*)+((?’-Open’\])[^\[\]]*)+)*(?(Open)(?!))\],{0,1} Test […]