当前位置:网站首页>Using go language to build web server
Using go language to build web server
2022-04-23 02:30:00 【Tian Tudou】
Let's start with a simple example , How to use Go Language to build a simple Web service , From shallow to deep , Introduce the implementation details
A simple Web The server
package main
import (
"fmt"
"log"
"net/http"
)
func HelloWorld(w http.ResponseWriter, r *http.Request) {
_, err := fmt.Fprintf(w, "Hello World!")
if err != nil {
log.Panic(err)
}
}
func main() {
// Set access routes , This is when url The path in is /hello when , Server calls HelloWorld function ( It can be uniformly called handler function )
http.HandleFunc("/hello", HelloWorld)
//web The listening port is 8080
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Panic(err)
}
}
here web The listening port is 8080, Run the program . Then open the browser , Input http://127.0.0.1:8080/hello, We will get the following results
Web How the server works
1、 First of all to see HandleFunc function , Look at the notes and you probably know HandleFunc It's for registration handler function ( It can also be called app, Corresponding to the previous HelloWorld function , Used to process user requests , And return the result ), Two into the refs , One pattern( It is simply understood as url The path in ), One handler function
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
2、DefaultServerMux It's a ServeMux Structural instance , Mainly used to store pattern and handler The correspondence between
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {
h Handler
pattern string
}
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
3、HandleFunc The function is called ServeMux Method of implementation HandleFunc
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
if handler == nil {
panic("http: nil handler")
}
mux.Handle(pattern, HandlerFunc(handler))
}
notes :mux.Handle(pattern, HandlerFunc(handler)) In this business HandlerFunc Is a function type , take handler Cast
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
4、ServeMux Realized Handle Method , Mainly using fields m(map[string]muxEntry) Storage pattern and handler The relationship between , The key is pattern, The value is handler
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("http: invalid pattern")
}
if handler == nil {
panic("http: nil handler")
}
if _, exist := mux.m[pattern]; exist {
panic("http: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
e := muxEntry{
h: handler, pattern: pattern}
mux.m[pattern] = e
if pattern[len(pattern)-1] == '/' {
mux.es = appendSorted(mux.es, e)
}
if pattern[0] != '/' {
mux.hosts = true
}
}
5、ListenAndServe The function is to listen and respond to requests
func ListenAndServe(addr string, handler Handler) error {
server := &Server{
Addr: addr, Handler: handler}
return server.ListenAndServe()
}
There are two of them , One is the listening address , One is handler, Notice the handler Refer to mux( Router , Used to store pattern and app The relationship between ). If handler by nil, Description default use DefautServeMux, Next, we can also construct a mux
package main
import (
"fmt"
"log"
"net/http"
)
func HelloWorld(w http.ResponseWriter, r *http.Request) {
_, err := fmt.Fprintf(w, "Hello World!")
if err != nil {
log.Panic(err)
}
}
func main() {
// Customize a mux
mux := new(http.ServeMux)
// Register function
mux.HandleFunc("/hello", HelloWorld)
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Panic(err)
}
}
Run the program , Then open the browser , Input http://127.0.0.1:8080/hello, It will also get the expected results
版权声明
本文为[Tian Tudou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230226013677.html
边栏推荐
- How many steps are there from open source enthusiasts to Apache directors?
- Talk about current limiting
- Leetcode39 combined sum
- Halo open source project learning (I): project launch
- 小程序 canvas 画布半圆环
- Leetcode46 Full Permutation
- [chrome extender] content_ Cross domain problem of script
- 在MySQL Workbench中执行外部的SQL脚本,报错
- C standard library - < time h>
- LeetCode 283. Move zero (simple, array) Day12
猜你喜欢
Understanding process (multithreading primary)
Want to experience homekit smart home? Why don't you take a look at this smart ecosystem
Arduino esp8266 network upgrade OTA
使用Go语言构建Web服务器
Kubernetes cluster installation based on Kirin SP10 server version
电源电路设计原来是这么回事
The usage and difference of * and & in C language and the meaning of keywords static and volatile
001_ Redis set survival time
Talk about current limiting
下载正版Origin Pro 2022 教程 及 如何 激 活
随机推荐
Lane cross domain problem
定了,今日起,本号粉丝可免费参与网易数据分析培训营!
类初始化和实例初始化面试题
都是做全屋智能的,Aqara和HomeKit到底有什么不同?
005_ redis_ Set set
智能辅助功能丰富,思皓X6安全配置曝光:将于4月23日预售
005_redis_set集合
十六、异常检测
001_ Redis set survival time
Hyperscan -- 2 compilation
Kubernetes cluster installation based on Kirin SP10 server version
Arduino esp8266 network upgrade OTA
Applet canvas canvas half ring
每日一题(2022-04-22)——旋转函数
R language advanced | generalized vector and attribute analysis
Synchronized锁及其膨胀
Tp6 Alibaba cloud SMS window reports curl error 60: SSL certificate problem: unable to get local issuer certificate
Daily question (April 22, 2022) - rotation function
假如404页面是这样的 | 每日趣闻
SQL server2019 cannot download the required files, which may indicate that the version of the installer is no longer supported. What should I do