- Building RESTful Web services with Go
- Naren Yellavula
- 208字
- 2021-07-02 20:14:07
Understanding Go's net/http package
Go's net/http package deals with HTTP client and server implementations. Here, we are mainly interested in the server implementation. Let us create a small Go program called basicHandler.go that defines the route and a function handler:
package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func MyServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", MyServer)
log.Fatal(http.ListenAndServe(":8000", nil))
}
This code does the following things:
- Create a route called /hello.
- Create a handler called MyServer.
- Whenever the request comes on the route (/hello), the handler function will be executed.
- Write hello, world to the response.
- Start the server on port 8000. ListenAndServe returns error if something goes wrong. So log it using log.Fatal.
- The http package has a function called HandleFunc, using which we can map an URL to a function.
- Here, w is a response writer. A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
- req is a request object, which deals with all the properties and methods of an HTTP request.
Use the log function to debug potential errors. The ListenAndServe function returns an error if there are any.
推薦閱讀
- Building E-commerce Sites with VirtueMart Cookbook
- 工業控制網絡安全技術與實踐
- Oracle SOA Suite 11g Performance Tuning Cookbook
- 局域網組建、管理與維護項目教程(Windows Server 2003)
- 網絡安全技術與解決方案(修訂版)
- 物聯網安全技術
- 物聯網技術與應用
- Spring 5.0 Projects
- 6G新技術 新網絡 新通信
- 網管工具使用與技巧大全
- jQuery Mobile Web Development Essentials
- TD-LTE無線網絡規劃與設計
- 紅藍攻防:構建實戰化網絡安全防御體系
- 網絡AI+:2030后的未來網絡
- 局域網組成實踐