Skip to content

Commit

Permalink
Refactoring into contextrouter & change of default app architectures …
Browse files Browse the repository at this point in the history
…to OOP

This commit introduces several breaking changes in the API to improve architecture and stability
a. Refactored server as two packages - contextrouter and server for upcoming "noserver" option
b. Changed the use of context.Context to purely request scoped values as advised in the context package
c. Changed the architecture of the default example apps to an architecture more compatible with Java OOP
d. This architecture change also removes package globals
  • Loading branch information
srinathh committed Oct 7, 2015
1 parent a1956de commit a21bb66
Show file tree
Hide file tree
Showing 13 changed files with 119 additions and 137 deletions.
43 changes: 28 additions & 15 deletions cmd/mobilehtml5app/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,46 @@ import (
"net/http"
"time"
"github.com/srinathh/mobilehtml5app/contextrouter"
"github.com/srinathh/mobilehtml5app/server"
"golang.org/x/net/context"
)
const greetString = "greetstring"
// App implements a web server backend for an android app
type App struct {
srv *server.Server
}
var srv *server.Server
// NewApp returns an App
func NewApp() *App {
srv := server.NewServer()
srv.Router.HandleFunc(contextrouter.GET, "/", index)
srv.Router.HandleFunc(contextrouter.GET, "/:hellostring/:name", hello)
return &App{
srv: srv,
}
}
// Start is called by the native portion of the webapp to start the web server.
// It returns the server root URL (without the trailing slash) and any errors.
func Start() (string, error) {
srv = server.NewServer()
srv.HandleFunc(server.GET, "/", index)
srv.HandleFunc(server.GET, "/:name", hello)
return srv.Start("127.0.0.1:0", map[string]interface{}{greetString: "Namaste"})
func (app *App) Start() (string, error) {
return app.srv.Start("127.0.0.1:0")
}
// Stop is called by the native portion of the webapp to stop the web server.
func Stop() {
srv.Stop(time.Millisecond * 100)
func (app *App) Stop() {
app.srv.Stop(time.Millisecond * 100)
}
// These two are autogenerated sample handlers for your webapp to get you started.
func index(_ context.Context, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("<html><body><div><a href='/Alice'>Alice</a></div><div><a href='/Bob'>Bob</a></div></body></html>"))
w.Write([]byte("<html><body><div><a href='/Namaste/Alice'>Alice</a></div><div><a href='/Hello/Bob'>Bob</a></div></body></html>"))
}
func hello(c context.Context, w http.ResponseWriter, r *http.Request) {
name := c.Value("name")
greetstring := c.Value(greetString)
greetstring := c.Value("hellostring")
fmt.Fprintf(w, "<html><body><div>%s %s!</div><div><a href='/'>Back</a></div></body></html>", greetstring, name)
}
`
Expand Down Expand Up @@ -193,6 +202,7 @@ import go.{{.PkgName}}.{{.ClsName}};
public class Main extends Activity {
private WebView mWebView;
private {{.ClsName}}.App mSrv;
@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -208,8 +218,9 @@ public class Main extends Activity {
@Override
protected void onResume() {
super.onResume();
mSrv = {{.ClsName}}.NewApp();
try {
mWebView.loadUrl({{.ClsName}}.Start() + "/");
mWebView.loadUrl(mSrv.Start() + "/");
} catch (Exception e) {
Toast.makeText(this,"Error:"+e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
Expand All @@ -222,7 +233,7 @@ public class Main extends Activity {
@Override
protected void onPause() {
super.onPause();
{{.ClsName}}.Stop();
mSrv.Stop();
}
@Override
Expand Down Expand Up @@ -254,6 +265,7 @@ import go.{{.PkgName}}.{{.ClsName}};
public class Main extends Activity {
private XWalkView mWebView;
private {{.ClsName}}.App mSrv;
@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -271,8 +283,9 @@ public class Main extends Activity {
mWebView.onShow();
}
mSrv = {{.ClsName}}.NewApp();
try {
mWebView.load({{.ClsName}}.Start() + "/", null);
mWebView.load(mSrv.Start() + "/", null);
} catch (Exception e) {
Toast.makeText(this,"Error:"+e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
Expand All @@ -289,7 +302,7 @@ public class Main extends Activity {
mWebView.pauseTimers();
mWebView.onHide();
}
{{.ClsName}}.Stop();
mSrv.Stop();
}
@Override
Expand Down
Binary file modified example/basic/androidapp/libs/backend.aar
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

public class Main extends Activity {
private WebView mWebView;
private Basic.App mSrv;

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -28,8 +29,9 @@ protected void onCreate(Bundle savedInstanceState) {
@Override
protected void onResume() {
super.onResume();
mSrv = Basic.NewApp();
try {
mWebView.loadUrl(Basic.Start() + "/");
mWebView.loadUrl(mSrv.Start() + "/");
} catch (Exception e) {
Toast.makeText(this,"Error:"+e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
Expand All @@ -42,7 +44,7 @@ protected void onResume() {
@Override
protected void onPause() {
super.onPause();
Basic.Stop();
mSrv.Stop();
}

@Override
Expand Down
14 changes: 0 additions & 14 deletions example/basic/local.go

This file was deleted.

26 changes: 18 additions & 8 deletions example/basic/webapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,30 @@ import (
"golang.org/x/net/context"
)

var srv *server.Server
// App implements a web server backend for an android app
type App struct {
srv *server.Server
}

// Start is called by the native portion of the webapp to start the web server.
// It returns the server root URL (without the trailing slash) and any errors.
func Start() (string, error) {
srv = server.NewServer()
// NewApp returns an App
func NewApp() *App {
srv := server.NewServer()
srv.Router.HandleFunc(contextrouter.GET, "/", index)
srv.Router.HandleFunc(contextrouter.GET, "/:hellostring/:name", hello)
return srv.Start("127.0.0.1:0")
return &App{
srv: srv,
}
}

// Start is called by the native portion of the webapp to start the web server.
// It returns the server root URL (without the trailing slash) and any errors.
func (app *App) Start() (string, error) {
return app.srv.Start("127.0.0.1:0")
}

// Stop is called by the native portion of the webapp to stop the web server.
func Stop() {
srv.Stop(time.Millisecond * 100)
func (app *App) Stop() {
app.srv.Stop(time.Millisecond * 100)
}

// These two are autogenerated sample handlers for your webapp to get you started.
Expand Down
25 changes: 1 addition & 24 deletions example/todoapp/androidapp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,17 @@ android {

android {
defaultConfig {
minSdkVersion 15
minSdkVersion 19
}
}

repositories {
maven {
url 'https://download.01.org/crosswalk/releases/crosswalk/android/maven2'
}
flatDir{
dirs 'libs'
}
}

dependencies {
compile 'org.xwalk:xwalk_core_library:14.43.343.17'
compile(name:'backend', ext:'aar')
}

Expand All @@ -45,23 +41,4 @@ task genGoMobileAAR(type:Exec) {
commandLine 'gomobile', 'bind', '-o', 'androidapp/libs/backend.aar', '.'
}

task compileJSX(type:Exec){
workingDir '../data'
commandLine 'babel', '-o','res/app/components.js', 'res/app/components.jsx'
}

task rebuildBinData(type:Exec){
workingDir '../data'
commandLine 'go-bindata' ,'-nocompress', '-prefix', 'res', 'res/...'
}

task fixPackageName(type:Exec){
workingDir '../data'
commandLine 'sed', '-i' ,'s/package main/package data/g', 'bindata.go'

}

rebuildBinData.dependsOn(compileJSX)
fixPackageName.dependsOn(rebuildBinData)
genGoMobileAAR.dependsOn(fixPackageName)
preBuild.dependsOn(genGoMobileAAR)
Binary file modified example/todoapp/androidapp/libs/backend.aar
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
Expand All @@ -17,10 +16,10 @@

public class Main extends Activity {
private WebView mWebView;
private Todoapp.App mSrv;

@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("lifecycleLogging","in onCreate");
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
WebSettings webSettings = mWebView.getSettings();
Expand All @@ -32,11 +31,11 @@ protected void onCreate(Bundle savedInstanceState) {
// We start the server on onResume
@Override
protected void onResume() {
Log.d("lifecycleLogging","in onResume");
super.onResume();
File d = getFilesDir();
try {
File fil = this.getFilesDir();
mWebView.loadUrl(Todoapp.Start(fil.getPath()) + "/", null);
mSrv = Todoapp.NewApp(d.getPath());
mWebView.loadUrl(mSrv.Start() + "/");
} catch (Exception e) {
Toast.makeText(this,"Error:"+e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
Expand All @@ -48,14 +47,12 @@ protected void onResume() {
// to be called by Android while onStop or onDestroy may not be called.
@Override
protected void onPause() {
Log.d("lifecycleLogging","in onPause");
super.onPause();
Todoapp.Stop();
mSrv.Stop();
}

@Override
protected void onDestroy() {
Log.d("lifecycleLogging","in onDestroy");
super.onDestroy();
}

Expand Down
2 changes: 1 addition & 1 deletion example/todoapp/androidapp/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Golang Todo App</string>
<string name="app_name">GoLang Todo App</string>
</resources>
16 changes: 6 additions & 10 deletions example/todoapp/items.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ func (s itemSorter) Less(i, j int) bool {

func (s itemSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func fetchAll(c context.Context, w http.ResponseWriter, r *http.Request) {
bend := c.Value(backendptr).(backend)

items, err := bend.fetchAll()
func (a *App) fetchAll(c context.Context, w http.ResponseWriter, r *http.Request) {
items, err := a.bk.fetchAll()
if err != nil {
log.Printf("fetchAll: error fetching items: %s", err)
http.Error(w, "", http.StatusInternalServerError)
Expand All @@ -76,7 +74,7 @@ func fetchAll(c context.Context, w http.ResponseWriter, r *http.Request) {
}
}

func createItem(c context.Context, w http.ResponseWriter, r *http.Request) {
func (a *App) createItem(c context.Context, w http.ResponseWriter, r *http.Request) {
var i item
if err := json.Unmarshal([]byte(r.PostFormValue("data")), &i); err != nil {
log.Printf("createItem: error decoding item: %s\n", err)
Expand All @@ -93,18 +91,16 @@ func createItem(c context.Context, w http.ResponseWriter, r *http.Request) {
return
}

bend := c.Value(backendptr).(backend)
if err := bend.create(i); err != nil {
if err := a.bk.create(i); err != nil {
log.Println(err)
http.Error(w, "", http.StatusBadRequest)
return
}
}

func deleteItem(c context.Context, w http.ResponseWriter, r *http.Request) {
func (a *App) deleteItem(c context.Context, w http.ResponseWriter, r *http.Request) {
id := c.Value("itemid").(string)
bend := c.Value(backendptr).(backend)
if err := bend.delete(id); err != nil {
if err := a.bk.delete(id); err != nil {
log.Println(err)
http.Error(w, "", http.StatusBadRequest)
return
Expand Down
7 changes: 6 additions & 1 deletion example/todoapp/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import (

func main() {
tmpdir := "/tmp"
appurl, err := todoapp.Start(tmpdir)
app, err := todoapp.NewApp(tmpdir)
if err != nil {
log.Fatal("Error creating app: %s", err)
}

appurl, err := app.Start()
if err != nil {
log.Fatalf("Error starting server: %s", err)
}
Expand Down
4 changes: 2 additions & 2 deletions example/todoapp/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ func fitCropScale(i image.Image, r image.Rectangle) image.Image {
return imaging.Resize(imaging.Crop(i, sliceRect), r.Dx(), r.Dy(), imaging.Lanczos)
}

func serveBg(c context.Context, w http.ResponseWriter, r *http.Request) {
bg := c.Value(bgimg).(image.Image)
func (a *App) serveBg(c context.Context, w http.ResponseWriter, r *http.Request) {
bg := a.bg

width, err := strconv.Atoi(c.Value("width").(string))
if err != nil {
Expand Down
Loading

0 comments on commit a21bb66

Please sign in to comment.