Categorygithub.com/grokify/twiml
modulepackage
1.1.2
Repository: https://github.com/grokify/twiml.git
Documentation: pkg.go.dev

# README

TwiML

Go Doc CircleCI

A library for producing TwiML XML markup for use with the Twilio API. This library can generate TwiML responses and provides helpers for processing callbacks and requests from Twilio.

This library does not yet cover the entire TwiML API, but pull requests are welcome if you find something missing.

Processing a request from Twilio

The library contains helpers to bind incoming Twilio requests to a struct that includes all of the available info from the request. Most initial requests from Twilio are of type twiml.VoiceRequest. Other request types are possible as a result of callbacks you register in your response. See the GoDoc for details.

func(w http.ResponseWriter, r *http.Request) {
    var vr twiml.VoiceRequest
    if err := twiml.Bind(&vr, r); err != nil {
        http.Error(w, http.StatusText(400), 400)
        return
    }
    fmt.Printf("Incoming call from %s", vr.From)
}

Constructing a response using TwiML

Once you receive a request from the Twilio API, you construct a TwiML response to provide directions for how to deal with the call. This library includes (most of) the allowable verbs and rules to validate that your response is constructed properly.

// CallRequest will return XML to connect to the forwarding number
func CallRequest(cfg Config) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {

        // Bind the request
        var cr twiml.VoiceRequest
        if err := twiml.Bind(&cr, r); err != nil {
            http.Error(w, http.StatusText(400), 400)
            return
        }

        // Create a new response container
        res := twiml.NewResponse()

        switch status := cr.CallStatus; status {

        // Call is already in progress, tell Twilio to continue
        case twiml.InProgress:
            w.WriteHeader(200)
            return

        // Call is ringing but has not been connected yet, respond with
        // a forwarding number
        case twiml.Ringing, twiml.Queued:
            // Create a new Dial verb
            d := twiml.Dial{
                Number:   cfg.ForwardingNumber,
                Action:   "action/",
                Timeout:  15,
                CallerID: cr.To,
            }

            // Add the verb to the response
            res.Add(&d)
            
            // Validate and encode the response.  Validation is done
            // automatically before the response is encoded.
            b, err := res.Encode()
            if err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }

            // Write the XML response to the http.ReponseWriter
            if _, err := w.Write(b); err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            w.Header().Set("Content-Type", "application/xml")
            w.WriteHeader(200)
            return

        // Call is over, hang up
        default:
            res.Add(&twiml.Hangup{})
            b, err := res.Encode()
            if err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            if _, err := w.Write(b); err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            w.Header().Set("Content-Type", "application/xml")
            w.WriteHeader(200)
            return
        }
    }
}

The example above shows the general flow of constructing a response. Start with creating a new response container, then use the Add() method to add a TwiML verb with its appropriate configuration. Verbs that allow other verbs to be nested within them expose their own Add() method. On the call to Encode() the complete response is validated to ensure that the response is properly configured.

More examples

For a more detailed example of constructing a small TwiML response server, see my Twilio Voice project which is a Google-voice clone that forwards calls to your number and handles transcribing voicemails.

# Functions

AllowedCallbackEvent validates that the CallbackEvent is one of the allowed options.
AllowedLanguage validates that the combination of speaker and language is allowable.
AllowedMethod validates that a method is either of type GET or POST (or empty string to default).
Bind will marshal a callback request from the Twilio API into the cbRequest struct provided.
IntBetween validates that a field is an integer between high and low.
NewResponse creates new response container.
Numeric validates that a string contains only digits 0-9.
NumericOpt validates that the field is numeric or empty string (for optional fields).
NumericOrWait validates that a string contains only digits 0-9 or the wait key 'w'.
OneOf validates that a field is one of the options provided.
OneOfOpt validates that a field is one of the options provided or the empty string (for optional fields).
Required validates that a field is not the empty string.
Validate aggregates the results of individual validation functions and returns true when all validation functions pass.

# Constants

Language and speaker options.
Call status.
Call status.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Call status.
Language and speaker options.
Trim options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Call status.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Call directions.
Call status.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Call status.
Language and speaker options.
Call directions.
Call directions.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Call status.
Call status.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Language and speaker options.
Trim options.
Language and speaker options.

# Variables

callback events valid for Conference TwiML block.
callback events valid for Sip TwiML block.

# Structs

Twilio Client TwiML.
Conference TwiML.
Dial TwiML.
DialActionRequest represents a request as a result of declaring an `action` URL on the Dial verb.
Enqueue TwiML.
Gather TwiML.
Hangup TwiML.
Leave TwiML.
Number TwiML.
Twilio Client Parameter TwiML.
Pause TwiML.
Play TwiML.
Queue TwiML.
Record TwiML.
RecordActionRequest represents a request as a result of declaring an `action` URL on a Record verb.
RecordingStatusCallbackRequest represents a request as a result of declaring a `recordingStatusCallback` on a Record verb.
Redirect TwiML.
Reject TwiML.
Response container for other TwiML verbs.
Say TwiML.
Sip TwiML.
Sms TwiML sends an SMS message.
TranscribeCallbackRequest represents a request as a result of declaring a `transcribeCallback` on a Record verb.
ValidationError will return one or more errors encountered during validation.
VoiceRequest represents the standard request format for callbacks received from the Twilio API.

# Interfaces

Markup interface is satisfied by valid TwiML verbs.