Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Golang to build web Services

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how to use Golang to build web services. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Let's first look at an example: http.go

Package mainimport ("fmt"io"log"net/http") func main () {http.HandleFunc ("/ test", doRequest) / / set access routing err: = http.ListenAndServe (": 8000", nil) / / set listening port if err! = nil {log.Fatal ("ListenAndServe:", err)} func doRequest (w http.ResponseWriter) R * http.Request) {r.ParseForm () / / parse the parameters passed by url For POST, parse the body of the response package (request body) / / fmt.Println (r.Form) / / these messages are printed information / / fmt.Println ("path", r.URL.Path) / / fmt.Println ("scheme", r.URL.Scheme) / / for k, v: = range r.Form {/ / fmt.Println ("key:", k) / / fmt.Println ("value:" Strings.Join (v, ")) / /} fmt.Fprintf (w," service start... ") / / what is written to w is output to the client or you can use the following io.WriteString object / / Note: if the ParseForm method is not called The following cannot get the data of the form / / query: = r.URL.Query () var uid string / / initialize the definition variable if r.Method = = "GET" {uid = r.FormValue ("uid")} else if r.Method = = "POST" {uid = r.PostFormValue ("uid")} io.WriteString (w, "uid =" + uid)}

The go run http.go command runs the program.

Then enter the address: http://127.0.0.1:8000/test?uid=10086 in the browser to see the result.

In the main function, we call a http.HandleFucn function from the net/http package to register a handler

This function takes two arguments. The first one is a string, and this is for route matching, and here I am / test route. The second parameter is the signature of a func (ResponseWriter, Request).

This is the signature of our doRequest function. The http.ListenAndServe (": 8000", nil) in the next line listens to port 8000 of localhost and ignores nil for the time being.

We have two parameters in the doRequest function, one of type http.ResponseWriter. It is similar to the response flow and is actually an interface type.

The second is the http.Request type, which is similar to HTTP requests. We don't have to use all the parameters, if it's just a simple output, then we just need to use http.ResponseWriter,io.WriteString, which will write the output stream to the data.

Let's change it a little bit, please pay attention to the modified part (here we only adjust part of the code of the main function)

Func main () {mux: = http.NewServeMux () mux.HandleFunc ("/ test", doRequest) err: = http.ListenAndServe (": 8000", mux) / / set the listening port if err! = nil {log.Fatal ("ListenAndServe:", err)}}

In this example, we no longer use nil in the function http.ListenAndServe. This example is actually the same as the above example. ServeMux is used to register the hanlder function mode with http.

Let's take a look at a more complex example:

Package mainimport ("fmt"io"log"net/http") var mux map [string] func (http.ResponseWriter, * http.Request) func main () {server: = http.Server {Addr: ": 8000", Handler: & doHandler {},} mux = make (map [string] func (http.ResponseWriter) * http.Request) mux ["/ test"] = doRequest err: = server.ListenAndServe () if err! = nil {log.Fatal ("ListenAndServe:", err)}} type doHandler struct {} func (* doHandler) ServeHTTP (w http.ResponseWriter, r * http.Request) {if res, ok: = mux [r.URL.String ()] Ok {res (w, r) return} io.WriteString (w, "url params:" + r.URL.String ())} func doRequest (w http.ResponseWriter, r * http.Request) {r.ParseForm () / / parses the parameters passed by url For POST, parse the request body of the response package (request body) fmt.Fprintf (w, "service start...") / / what is written to w is output to the client, or you can use the following io.WriteString object}

Instead of defining ServeMux for this example, we use http.Server. All run the server with the net/http package.

These are all the contents of the article "how to use Golang to build web Services". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report