Several ways to write Web server in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Let's talk about the differences between Web server and HTTP server. HTTP server, as the name implies, supports HTTP protocol servers, and Web server may support other network protocols in addition to the HTTP protocol. This article only discusses several common ways to write Web server using the official package of Golang.

The simplest HTTP server

This is also the simplest way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Package   main

Import (
"Net/http"
"Log"
)

func MyHandler (w http. Responsewriter, R *http. Request) {
FMT. fprintf (W, "Hello there!\n")
}

func Main () {
http. Handlefunc ("/", MyHandler)//Set access route
log. Fatal (http. Listenandserve (": 8080", nil))
}

Start the program, open another terminal input command curl localhost:8080 , or directly open localhost:8080 the browser, you can seeHello there!

The Listenandserve function listens for and processes connections. The internal processing is handled by a goroutine for each connection. In fact, this is not a good way to deal with. Students who have studied the operating system know that the cost of process or thread switching is enormous. Although Goroutine is a user-level lightweight thread, switching does not result in user-state and kernel-state switching, but the cost of switching when the Goroutine number is huge is not negligible. A better way to do this is to use Goroutine pool, where you hold down the table.

Using the Handler interface

The way it feels can be too small, for example, I want to set the server timeout time can not be set. This is when we can use the custom server.

1
2
3
4
5
6
7
8
9
10
11
12
 type Server struct {
Addrstring//tcp address to listen on
Handlerhandler//handler to invoke
readtimeouttime.duration//maximum Duration before timing out read of the request
writetimeout time. Duration//maximum Duration before timing out write of the response
Tlsconfig*tls. Config
...
}
//handler is a interface, defined as follows
type Handler interface {
servehttp (Responsewrite, *request)
}

So as long as we implement the handler interface method, ServeHTTP we can customize our server. The sample code is as follows.

 1  
2
3
4
5
6
7
8
9
10
11
12
13
Span class= ' line ' >14
15
16
17
 type  myhandler  struct  { 

}

func (this MyHandler) servehttp (w responsewrite, R *request) {



func Main () {
server: = http. server{
Addr:,
handler:&myhandler{},
Readtimeout:3 *time. Second,


log. Fatal (server. Listenandserve)

Direct processing of Conn

Sometimes we need to deal with connection at a lower level, so we can use net packages. The server-side code is simply implemented as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 func  main () { 
Listener, err: = Net. Listen ( "TCP" , )
span class= "keyword" >if err! = nil {
log. Fatal (Err)
}

for {
conn, err: = Listener. Accept ()
if err! = nil {
//handle error
}< /span>
go handleconn (conn)
}

For the sake of the example, I have a goroutine to deal with each of the connection. In practical use, goroutine pool is often a better choice. For the return information of the client we'll just have to rest back in Conn.

Proxy

Above said several kinds of Web server implementation, the following simple implementation of an HTTP proxy, with Golang write proxy is very simple just need to conn forward.

1
2
3
4
5
6
7
8
9
Ten
One
A
-
-
the
-
-
-
+
-
+
A
at
-
-
-
-
-
in
-
to
+
-
the
*
$
Panax Notoginseng
-
the
+
A
//Proxy Server
func Main () {
Listener, err: = Net. Listen ("TCP", ": 8080")
if err! = Nil {
log. Fatal (ERR)
}

For {
conn, err: = Listener. Accept ()
if err! = Nil {
//handle Error
}
Go handleconn (conn)
}
}

func handleconn (from net. Conn) {
to, err: = Net. Dial ("TCP", ": 8001")//establish and connect to the target server
if err! = Nil {
//handle Error
}

Done : = make (chan struct{})

go func() {
defer from. Close ()
defer to. Close ()
io. Copy (from, to)
done<-strcut{}{}
}()

go func() {
defer from. Close ()
defer to. Close ()
io. Copy (to, from)
done<-struct{} {}
}

<-done
<-done
}

Proxy a little bit of reinforcement can be achieved # not to describe the purpose of #.

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.