This is a creation in Article, where the information may have evolved or changed.
From TYLERCHR ' s Coming in Go 1.8.
With the development of Go 1.8 new features already frozen, go 1.8 will be released around February 2017, now let's look at some of the more interesting API changes in Go 1.8.
HTTP Server Connection draining
Brad Fitzpatrick recently closed a nearly four-year-old issue, which issue requested to implement http.Server
the connection exhaustion (draining) feature. Now the call can be srv.Close
stopped immediately http.Server
, or it can be called to srv.Shutdown(ctx)
wait for an existing connection to finish (exhausted, draining, github.com/tylerb/graceful users should be familiar with this feature).
In the following example, the server SIGINT
gracefully shuts down when the signal is received ( ^C
).
1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
PackageMainImport("Context""IO""Log""Net/http""OS""Os/signal""Time")funcMain () {//Subscribe to SIGINT signalsStopchan: = Make(ChanOs. Signal) Signal. Notify (Stopchan, OS. Interrupt) Mux: = http. Newservemux () Mux. Handle ("/", HTTP. Handlerfunc (func(W http. Responsewriter, R *http. Request) {time. Sleep(5* Time. Second) io. WriteString (W,"finished!")) SRV: = &http. SERVER{ADDR:": 8081", Handler:mux}Go func() {//Service ConnectionsifERR: = srv. Listenandserve (); Err! =Nil{log. Printf ("Listen:%s\n", err)}} () <-stopchan//wait for SIGINTLog. Println ("shutting down server ...")//Shut down gracefully, but wait no longer than 5 seconds before haltingCTX, _: = Context. Withtimeout (context. Background (),5*time. Second) srv. Shutdown (CTX) log. Println ("Server gracefully stopped")} |
Once the SIGINT
signal is received, the server immediately stops accepting the new connection and srv.ListenAndServe()
returns http.ErrServerClosed
. srv.Shutdown
will block until all outstanding request is processed and their underlying connection is closed.
More complex processing can be achieved by context
implementing, for example, using context.Timeout
the maximum shutdown wait time. You can try to copy the example in Https://github.com/tylerchr/examples/tree/master/draining and implement it.
By http.Pusher
implementing http/2.0 server Push
http/2.0 contains the server Push attribute, which allows the HTTP/2 server to proactively send additional HTTP response to the client, even if the client does not send a request. The goal is that the server can promptly push the resources required by the client to the client without requesting the client. You can look at the wiki http/2 Server push for specific examples.
If a server is supported HTTP/2
, the interface provided to handler is http.ResponseWriter
implemented http.Pusher
. Handler can use this ribbon to trigger server Push, and virtual requests (synthetic request) can be registered with HTTP. Handled by the Server handler.
The following program is processed /index.html
and can be push one /static/gopher.png
:
123456789101112131415161718192021222324 |
PackageMainImport "Net/http"funcMain () {http. Handle ("/static/", HTTP. Stripprefix ("/static/", HTTP. Fileserver (http. Dir ("./static"))) HTTP. Handle ("/index.html", HTTP. Handlerfunc (func(W http. Responsewriter, R *http. Request) {//server push is available if W implements HTTP. PusherifP, OK: = W. (http. Pusher); OK {P.push ("/static/gopher.png",Nil}}//Load the main pageW.header (). Set ("Content-type","Text/html") W.write ([]byte(' ')})) http. Listenandservetls (": 4430","Cert.pem","Key.pem",Nil)} |
You can clone This example from Https://github.com/tylerchr/examples/serverpush, which is the result of a visit to Chrome 54:
Obviously you can see it in the Initiator column gopher.png
Push
, and you can see that the blue color gopher.png
precedes /index.html
being received, indicating that the resource was pushed to the client before the request. The HTML can be displayed when it is finished downloading
.
One might ask how to write a test to verify the Handler that implements Server push. http.NewTLSServer
It is not implemented because the HTTP/2 server is not started httptest.ResponseRecorder
http.Pusher
. My solution is the wrapper httptest.ResponseRecorder
implementation Pusher
interface, here's an example.
Database/sql
database/sql
The package has several major changes that allow users to better control database queries, allowing users to better utilize the characteristics of the database.
- Query can use
context.Context
Cancel query
- A pure database column type can be
sql.ColumnType
obtained by
- Queries can use named parameters if supported by the underlying database
More details can be found in Daniel Theophanes's article, what's new in Database/sql?, he made most of the changes.
Plugin package Implementation Dynamic Plug-in
The newly added standard library plugin
provides initial plug-in support, which allows the program to dynamically load plug-ins at runtime.
But this library still seems to be a lot of bugs, I can't even write a normal program to test it, but suppose it should be used like this:
1234567891011 |
//hexify.go package main import "Encoding/hex" func Hexify (in string ) string { Return hex. Encodetostring ([]byte (in))}$ go build-buildmode= Shared hexify. go
//produces hexify.so |
1234567891011 |
//Main.go Package mainimport"plugin"func Main () {p, _ = plugin. Open ("hexify.so") F: = P.lookup ("hexify") fmt. Println (F. (func(stringstring) ("gopher"))//676f70686572} |
In this example, the hexify.go
Hexify
function is implemented, it is compiled into a shared library, and the second program dynamically loads it. This allows the go program to not be able to invoke other libraries while compiling.
Alias
The alias (aliasing) was added to the Go 1.8 language specification, but is now removed to see the note: This post is from Russ Cox and may appear in Go 1.9.
This feature has also caused a lot of controversy,
指示符别名(Identifier aliasing)用来定义多个类型为同一个类型的语法。一个用处用来重构复杂的代码的时候,允许重新划分包而不必带来类型的不一致。 Ian Lance Taylor举了一个[例子](https://groups.google.com/d/msg/golang-dev/OmjsXkyOQpQ/OrcHWiGUBAAJ):
As a concrete example, the golang.org/x/net/context
process of moving an extension package to a standard library context
. Because the context is already widely used, it is difficult to convert all of the user's code uniformly, so it is necessary to allow the two packages to be common.
The aliases are defined as follows:
This syntax definition Foo
is an pkg.Bar
alias. Foo
can be used in any pkg.Bar
place that appears. For example, any type golang.org/x/net/context
of need can be replaced with a standard library, which context
is equivalent.
Aliases can also be used on types such as constants, variables, functions, and so on.
This is a controversial feature, and you can refer to issue 16339 and Golang-dev post for a discussion. Since it was removed from go 1.8, you can temporarily not focus on this feature.
New Slice Sort API
Unified slice sorted by the new sort. The Slice function is implemented. It allows arbitrary slice to be sorted, simply by providing a callback comparison function, rather than providing a specific implementation as before sort.Interface
. This function has no return value. Like other sort functions, it provides a sort of in situ.
The following example sorts the slice of the well-known peaks according to altitude.
12345678910111213141516171819202122 |
typePeakstruct{NamestringElevationint //In Feet}peaks: = []peak{{"Aconcagua",22838},{"Denali",20322},{"Kilimanjaro",19341},{"Mount Elbrus",18510},{"Mount Everest",29029},{"Mount Kosciuszko",7310},{"Mount Vinson",16050},{"Puncak Jaya",16024},}//Does an in-place sort on the peaks slice, with tallest peak firstSort. Slice (Peaks,func(I, Jint)BOOL{returnPeaks[i]. Elevation >= peaks[j]. Elevation})//Peaks is now sorted |
by sort.Interface
type Len()
and by Swap(i, j int)
providing an abstract sort type, which is the previous sort method, and Less(i, j int)
as a comparison callback function, can be simply passed to sort.Slice
the sorting.
Other
- 87B1AAA
encoding/base64
Encoder now has a strict mode.
- The 6BA5B32 is
expvar
exposed and can be used in other mux.
- 003a598 pseudo-Random codes can be
rand.Uint64()
generated (previously only supported by UInt32).
- 67ea710 adds a new
time.Until
function, and corresponds to it time.Since
.
net/http
intentionally only implemented using TLS HTTP/2, you can view [issue 14141]https://github.com/golang/go/issues/14141 () to learn the details.
sort.SliceStable
provides a stable sort of slice, just like before sort.Stable
.
Translator's added content
Go 1.8 A big feature is performance improvements, including binary file size, compile speed, and run speed.
And a very big boost is to provide less than 100US GC pauses.
net/http
Provides more time-out settings, such as ReadHeaderTimeout
, IdleTimeout
.
A complete list of changes: Go 1.8