-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Play with compiling existing Go packages using GopherJS and serving a…
…rchive objects over http with CORS. Related to gopherjs/gopherjs.github.io#26.
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// Play with compiling existing Go packages using GopherJS and serving archive objects over http with CORS. | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
|
||
gbuild "github.com/gopherjs/gopherjs/build" | ||
"github.com/gopherjs/gopherjs/compiler" | ||
) | ||
|
||
const prefix = "/pkg/" | ||
|
||
func main() { | ||
http.HandleFunc(prefix, handler) | ||
panic(http.ListenAndServe("localhost:8081", nil)) | ||
} | ||
|
||
func handler(w http.ResponseWriter, req *http.Request) { | ||
pkgPath := req.URL.Path[len(prefix) : len(req.URL.Path)-len(".a.js")] | ||
|
||
w.Header().Set("Access-Control-Allow-Origin", "*") | ||
w.Header().Set("Content-Type", "application/octet-stream") | ||
|
||
err := func() error { | ||
options := &gbuild.Options{CreateMapFile: false, Verbose: true} | ||
s := gbuild.NewSession(options) | ||
|
||
if _, err := s.ImportPackage(pkgPath); err != nil { | ||
return err | ||
} | ||
pkg := s.Packages[pkgPath] | ||
if err := compiler.WriteArchive(pkg.Archive, w); err != nil { | ||
return err | ||
} | ||
return nil | ||
}() | ||
fmt.Println(err) | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusNotFound) | ||
} | ||
} |